//
//  SQPageCollectionView.swift
//  SQPageView
//
//  Created by ToothBond on 2017/4/27.
//  Copyright © 2017年 rensq. All rights reserved.
//

import UIKit

protocol SQPageCollectionDataSource : class {
    
    func numberOfSectionInPageCollectionView(_ pageCollectionView : SQPageCollectionView) -> Int
    
    func pageCollectionView(_ pageCollectionView : SQPageCollectionView, numberOfItemsInSection section : Int) -> Int
    
    func pageCollectionView(_ pageCollectionView : SQPageCollectionView,_ collectionView : UICollectionView, cellForItemAt indexPath : IndexPath) -> UICollectionViewCell
}

class SQPageCollectionView: UIView {
    
    weak var dataSource : SQPageCollectionDataSource?
    fileprivate var collectionView : UICollectionView!
    fileprivate var pageControl : UIPageControl!
    fileprivate var titles : [String]
    fileprivate var style : SQPageStyle
    fileprivate var layout : SQPageCollectionLayout
    fileprivate var currentIndexPath = IndexPath(item: 0, section: 0)
    fileprivate var titleView : SQTitleView!

    init(frame: CGRect, titles : [String], style : SQPageStyle, layout : SQPageCollectionLayout) {
        self.titles = titles
        self.style = style
        self.layout = layout
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension SQPageCollectionView {
    fileprivate func setupUI() {
        //titleView
        let titleY = style.isTitleInTop ? 0 : bounds.height - style.titleHeight
        let titleFrame = CGRect(x: 0, y: titleY, width: bounds.width, height: style.titleHeight)
        let titleView = SQTitleView(frame: titleFrame, titles: titles, style: style)
        titleView.delegate = self
        addSubview(titleView)
        self.titleView = titleView
        //UICollectionView
        
        
        let collectionY = style.isTitleInTop ? style.titleHeight : 0
        let collectionH = bounds.height - style.titleHeight - style.pageControlHeight
        let collectionFrame = CGRect(x: 0, y: collectionY, width: bounds.width, height: collectionH)
        
        let collectionView = UICollectionView(frame: collectionFrame, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        addSubview(collectionView)
        self.collectionView = collectionView
        
        //PageControl
        let pageFrame = CGRect(x: 0, y: collectionView.frame.maxY, width: bounds.width, height: style.pageControlHeight)
        let pageControl = UIPageControl(frame: pageFrame)
        pageControl.numberOfPages = 4
        addSubview(pageControl)
        self.pageControl = pageControl
        
        titleView.backgroundColor = UIColor.randomColor()
        collectionView.backgroundColor = UIColor.randomColor()
        pageControl.backgroundColor = UIColor.randomColor()
    }
}

extension SQPageCollectionView {
    func registerClass(_ cell : AnyClass?, forCellReuseableIdentifier : String) {
        collectionView.register(cell, forCellWithReuseIdentifier: forCellReuseableIdentifier)
    }
    
    func registerNib(_ nib : UINib?, forCellReuseableIdentifier : String) {
        collectionView.register(nib, forCellWithReuseIdentifier: forCellReuseableIdentifier)
    }
    
    func reloadData() {
        collectionView.reloadData()
    }
}

extension SQPageCollectionView : UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return dataSource?.numberOfSectionInPageCollectionView(self) ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        guard let dataSource = dataSource else {return 0}
//        return dataSource.pageCollectionView(self, numberOfSection: section)
        
        let sectionItemCount = dataSource?.pageCollectionView(self, numberOfItemsInSection: section) ?? 0
        if  section == 0{
            pageControl.numberOfPages = (sectionItemCount - 1)/(layout.numberOfCol * layout.numberOfRow) + 1
        }
        return sectionItemCount
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = (dataSource?.pageCollectionView(self, collectionView, cellForItemAt: indexPath))!
        return cell
    }
}

extension SQPageCollectionView : UICollectionViewDelegate {
    //监听scrollView停止滚动
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollViewDidEndScroll()
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            scrollViewDidEndScroll()
        }
    }
    
    private func scrollViewDidEndScroll(){
        //获取滚动结束后，处于第几组，第几页
        
        //guard let indexPath = collectionView.indexPathsForVisibleItems.first else {return}    //系统bug 不一定能及时返回当前可见的cell
        
        let firstCellPoint = CGPoint(x: collectionView.contentOffset.x + layout.sectionInset.left + 1, y: layout.sectionInset.top + 1)
        guard let indexPath = collectionView.indexPathForItem(at: firstCellPoint) else {return}
        
        //判断是否需要改变组
        if indexPath.section != currentIndexPath.section {
            let itemsCount = dataSource?.pageCollectionView(self, numberOfItemsInSection: indexPath.section) ?? 0
            
            //改变titleView
            titleView.setCurrentIndex(indexPath.section)
            
            //改变pageControl
            pageControl.numberOfPages = (itemsCount - 1)/(layout.numberOfCol * layout.numberOfRow) + 1
            
        }
        
        pageControl.currentPage = indexPath.item / (layout.numberOfCol * layout.numberOfRow)
        
        currentIndexPath = indexPath
    }
}

extension SQPageCollectionView : SQTitleViewDelegate{
    func titleView(_ titleView: SQTitleView, targetIndex: Int) {
        let indexPath = IndexPath(row: 0, section: targetIndex)
        
        collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
        
        let itemInSection = dataSource?.pageCollectionView(self, numberOfItemsInSection: targetIndex) ?? 0
        
        //设置pageControl
        pageControl.numberOfPages = (itemInSection - 1) / (layout.numberOfRow * layout.numberOfCol) + 1
        pageControl.currentPage = 0
        
        currentIndexPath = indexPath
        
        //调整正确的位置
        collectionView.contentOffset.x -= layout.sectionInset.left
    }
}
